package com.chezai.client.activitys;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chezai.client.R;
import com.chezai.client.bean.ClassRecord;
import com.chezai.client.bean.CoachLoginRecord;
import com.chezai.client.bean.LedBean;
import com.chezai.client.bean.TerminalBaseInfo;
import com.chezai.client.bean.UserInfo;
import com.chezai.client.dao.manager.ClassRecordDaoManager;
import com.chezai.client.dao.manager.CoachLoginRecordDaoManager;
import com.chezai.client.dao.manager.TerminalBaseInfoDaoManager;
import com.chezai.client.dao.manager.UserInfoDaoManager;
import com.chezai.client.fragment.CoachTrainRecordFragment;
import com.chezai.client.fragment.LearnCarFragment;
import com.chezai.client.fragment.StudentInfoFragment;
import com.chezai.client.global.Const;
import com.chezai.client.global.NetConst;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.inter.ITwoAndThreeView;
import com.chezai.client.presenter.TwoAndThreePresenter;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.DialogUtils;
import com.chezai.client.widget.LoginTypeDialog;
import com.chezai.client.widget.NormalAlertDialog;
import com.chezai.client.widget.QRDialog;
import com.chezai.client.widget.ReadCardDialog;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tw.com.prolific.driver.pl2303.PL2303Driver;


/**
 * 科二科三首页
 * Created by likunyang on 2017/9/13.
 */

public class TwoAndThreeActivity extends BaseActivity<TwoAndThreePresenter, ITwoAndThreeView> implements ITwoAndThreeView, LoginTypeDialog.OnLoginTypeClickListener, ReadCardDialog.OnInputOverListener, QRDialog.OnCountDownTimerFinishListener, NormalAlertDialog.OnNormalAlertDialogListener {


    @BindView(R.id.image_avater)
    ImageView imageAvater;
    @BindView(R.id.tv_train_part)
    TextView tvTrainPart;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.btn_student_signin)
    Button bottomBtn;
    @BindView(R.id.btn_coach_signout)
    Button topBtn;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    Fragment mCurrentFragment;
    private QRDialog qrDialog;
    private long coachLoginRecordId;
    private UserInfo mCoachInfo;
    private UserInfo mStudentInfo;
    private String mCurrentTag;
    private Handler mLedHandler;
    private Runnable ledRunnable;
    private Callback.Cancelable cancelable;
    private PL2303Driver mSerial;
    private static final String ACTION_USB_PERMISSION = "com.prolific.pl2303hxdsimpletest.USB_PERMISSION";


    /**
     * 正常开始教学
     *
     * @param coachLoginRecordId 教练登录记录ID
     */
    public static void normalOpen(Activity from, long coachLoginRecordId) {
        Intent intent = new Intent(from, TwoAndThreeActivity.class);
        intent.putExtra("coachLoginRecordId", coachLoginRecordId);
        from.startActivity(intent);
    }

    /**
     * 非正常打开
     * 在教学过成功，终端掉电，重启
     *
     * @param classRecordId 学员课程记录ID
     * @param isEndTrain    是否结束训练，true 结束训练，false 继续训练
     */
    public static void unusualOpen(Activity from, long classRecordId, boolean isEndTrain) {
        Intent intent = new Intent(from, TwoAndThreeActivity.class);
        intent.putExtra("classRecordId", classRecordId);
        intent.putExtra("isEndTrain", isEndTrain);
        from.startActivity(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (outState != null) {
            String FRAGMENTS_TAG = "android:support:fragments";
            outState.remove(FRAGMENTS_TAG);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_subject_two_three;
    }

    /**
     * 在 LoginActivity
     * 如果是科二科三 ，并且查找到课程记录表中有未结束的培训，并且选择了继续训练
     */
    @Override
    public void initView(Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey("classRecordId")) {
                long classRecordId = bundle.getLong("classRecordId");
                boolean isEndTrain = bundle.getBoolean("isEndTrain");
                ClassRecord classRecord = ClassRecordDaoManager.getInstance().findClassRecord(classRecordId);
                switchFragment(Const.LEARN_CAR_FRAGMENT_TAG, classRecordId, classRecord.getTrainPart() == Const.TrainPart.TWO ? "第二部分" : "第三部分", isEndTrain);
            } else {
                coachLoginRecordId = bundle.getLong("coachLoginRecordId");
                switchFragment(Const.COACH_TRAIN_RECORD_FRAGMENT_TAG, coachLoginRecordId, "", true);
            }
        }


    }

    public void setUserInfo(UserInfo userInfo) {
        Glide.with(this).load(userInfo.getPhotoUrl()).into(imageAvater);
        if (userInfo.getUserType() == UserInfo.USER_COACH) {
            mCoachInfo = userInfo;
            tvName.setText("教练员：" + userInfo.getName());
        } else if (userInfo.getUserType() == UserInfo.USER_STUDENT) {
            mStudentInfo = userInfo;
            tvName.setText("学员：" + userInfo.getName());
        }
    }

    /**
     * 切换内容区域
     *
     * @param tag        Tag
     * @param trainPart  训练部分
     * @param isEndTrain 是否结束训练
     */
    @Override
    public void switchFragment(String tag, long _id, String trainPart, boolean isEndTrain) {
        if (TextUtils.equals(mCurrentTag, tag)) {
            return;
        } else {
            mCurrentTag = tag;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (Const.COACH_TRAIN_RECORD_FRAGMENT_TAG.equals(tag)) {//当前教练训练记录Fragment
            coachLoginRecordId = _id;
            setupButton(View.VISIBLE, View.VISIBLE, trainPart, R.mipmap.icon_stu_login, Const.COACH_TRAIN_RECORD_FRAGMENT_TAG);
            mCurrentFragment = CoachTrainRecordFragment.newInstance(_id);
            CoachLoginRecord coachLoginRecord = CoachLoginRecordDaoManager.getInstance().findCoachLoginRecord(coachLoginRecordId);
            setUserInfo(coachLoginRecord.getCoachInfo());
        } else if (Const.STUDENT_INFO_FRAGMENT_TAG.equals(tag)) {//学员信息Fragment
            setupButton(View.VISIBLE, View.GONE, trainPart, 0, Const.STUDENT_INFO_FRAGMENT_TAG);
            mCurrentFragment = StudentInfoFragment.newInstance(_id, coachLoginRecordId);
            setUserInfo(UserInfoDaoManager.getInstance().findUserInfoById(_id));
        } else if (Const.LEARN_CAR_FRAGMENT_TAG.equals(tag)) {//学车Fragment
            setupButton(View.GONE, View.VISIBLE, trainPart, R.mipmap.icon_change_part, Const.LEARN_CAR_FRAGMENT_TAG);
            mCurrentFragment = LearnCarFragment.newInstance(_id, isEndTrain);
            ClassRecord classRecord = ClassRecordDaoManager.getInstance().findClassRecord(_id);
            setUserInfo(classRecord.getUserInfo());
        }
        transaction.replace(R.id.fl_content, mCurrentFragment);
        transaction.commit();
    }


    private void setupButton(int topBtnVis, int bottomBtnVis, String topText, int resId, String tag) {
        bottomBtn.setVisibility(bottomBtnVis);
        bottomBtn.setBackgroundResource(resId);
        bottomBtn.setTag(tag);

        topBtn.setVisibility(topBtnVis);
        topBtn.setTag(tag);
        tvTrainPart.setVisibility(topBtnVis == View.VISIBLE ? View.GONE : View.VISIBLE);
        tvTrainPart.setText(topText);
    }

    @Override
    public void initData() {
        //推大屏
        // get service
        mSerial = new PL2303Driver((UsbManager) getSystemService(Context.USB_SERVICE), this, ACTION_USB_PERMISSION);
        // check USB host function.
        if (!mSerial.PL2303USBFeatureSupported()) {
            Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "No Support USB host API");
            mSerial = null;
        }
        if (mLedHandler == null) {
            mLedHandler = new Handler();
            ledRunnable = new LedRunnable(mLedHandler, mSerial);
        }
        mLedHandler.postDelayed(ledRunnable, 1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mSerial.isConnected()) {
            if (!mSerial.enumerate()) {
                Toast.makeText(this, "no more devices found", Toast.LENGTH_SHORT).show();
                return;
            } else {
                Log.d(TAG, "onResume:enumerate succeeded!");
            }
        }//if isConnected
        Toast.makeText(this, "attached", Toast.LENGTH_SHORT).show();

    }

    @Override
    protected void onDestroy() {
        if (mSerial != null) {
            mSerial.end();
            mSerial = null;
        }
        super.onDestroy();
        if (mLedHandler != null) {
            mLedHandler.removeCallbacks(ledRunnable);
        }
    }

    @Override
    public void setListener() {
        tvTrainPart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DeviceUtils.fastFiveClick() || !NetConst.RELEASE_SERVER) {
                    DebugActivity.openDebug(TwoAndThreeActivity.this);
                }
            }
        });
    }

    @Override
    public UserInfo getCoachInfo() {
        return mCoachInfo;
    }

    @Override
    public UserInfo getStudentInfo() {
        return mStudentInfo;
    }

    @Override
    public Fragment getCurrentFragment() {
        return mCurrentFragment;
    }

    @Override
    public void coachSignOutSucess() {
        LoginActivity.openLogin(this, null, null);
    }

    @OnClick({R.id.btn_coach_signout, R.id.btn_student_signin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_coach_signout://教练登出
                String btnCoachSignOutTag = (String) topBtn.getTag();
                if (!TextUtils.equals(Const.LEARN_CAR_FRAGMENT_TAG, btnCoachSignOutTag)) {
                    takeCoachSignOutPhoto();
                }
                break;
            case R.id.btn_student_signin://学员登录 or 更改项目
                String tag = (String) bottomBtn.getTag();
                if (TextUtils.equals(Const.LEARN_CAR_FRAGMENT_TAG, tag)) {
                    if (mCurrentFragment instanceof LearnCarFragment) {
                        ((LearnCarFragment) mCurrentFragment).showSelectTrainSubjectDialog();
                    }
                } else if (TextUtils.equals(Const.COACH_TRAIN_RECORD_FRAGMENT_TAG, tag)) {
                    showLoginType(true);
                }
                break;
        }
    }

    private void takeCoachSignOutPhoto() {
        CameraActivity.startCameraActivity(this
                , Const.TakePhotoMode.COUNT_DOWN_TIME, 2
                , Const.PhotoEventType.TEACHE_SIGN_OUT
                , 0, null
                , mCoachInfo.getName()
                , Const.CameraChannel.FONT, null, null, false);
    }

    /**
     * 学员人脸登录
     */
    public void takeStudentFaceLogin() {
        CameraActivity.startCameraActivity(this,
                Const.TakePhotoMode.FACE_DETECTION, 0
                , Const.PhotoEventType.STUDENT_FACE_LOGIN, 0, null
                , mCoachInfo.getName()
                , Const.CameraChannel.FONT, null, null, false);
    }

    /**
     * 弹出登陆方式
     */
    public void showLoginType(boolean isSign) {
        LoginTypeDialog dialog = new LoginTypeDialog(this);
        dialog.setLoginType(presenter.getLoginType());
        dialog.isSign(isSign);
        dialog.setOnLoginTypeClickListener(this);
        dialog.show();
    }

    @Override
    public void onLoginTypeClick(Dialog dialog, View v, short loginType) {
        dialog.dismiss();
        presenter.gotoLoginWithLoginType(loginType);
    }

    /**
     * 小鹿设备外接刷卡
     */
    @Override
    public void showReadCardDialog() {
        ReadCardDialog readCardDialog = new ReadCardDialog(this);
        readCardDialog.setOnInputOverListener(this);
        readCardDialog.show();
    }

    @Override
    public void onInputOver(Dialog dialog, String result) {
        dialog.dismiss();
        presenter.tell0x0401Tranmission(Const.LOGIN_TYPE_RFID, result);
    }

    /**
     * 展示二维码dialog
     */
    @Override
    public void showQRDialog(String qrUrl) {
        qrDialog = DialogUtils.showQRDialog(this, qrUrl, this);
        if (qrDialog == null) {
            showToast("二维码获取失败，请重新获取！");
        }
    }

    /**
     * 二维码展示框，倒计时完成时回调
     */
    @Override
    public void onCountDownTimerFinish(CountDownTimer countDownTimer) {
        presenter.tell0x0401Tranmission(Const.LOGIN_TYPE_APP, null);
    }

    @Override
    public void dissmissDialog() {
        if (qrDialog != null && qrDialog.isShowing()) {
            qrDialog.dismiss();
            qrDialog = null;
        }
    }

    //提示
    public void showAlertDialog(String content, int tag) {
        DialogUtils.showSingleButtonAlertDialog(this, "提示", content, "确定", NormalAlertDialog.Builder.DIALOG_STYLE_NORMAL, tag, this);
    }

    @Override
    public void onNormalAlertDialogClick(NormalAlertDialog dialog, View view, int btnType) {
        dialog.dismiss();
        if (btnType == NormalAlertDialog.NORMAL_ALERT_DIALOG_MIDDLE) {
            switch (dialog.getTag()) {
                case Const.PhotoEventType.STUDENT_SIGN_IN:
                    if (mCurrentFragment instanceof StudentInfoFragment) {
                        ((StudentInfoFragment) mCurrentFragment).takeStudentSignInPhoto();
                    }
                    break;
                case Const.PhotoEventType.STUDENT_SIGN_OUT:
                    if (mCurrentFragment instanceof LearnCarFragment) {
                        ((LearnCarFragment) mCurrentFragment).takeStudentSignOutPhoto();
                    }
                    break;
                case Const.PhotoEventType.STUDENT_LEARNING:
                    break;
                case Const.PhotoEventType.ZHUAPAI:
                    break;
                case Const.PhotoEventType.TEACHE_SIGN_OUT:
                    takeCoachSignOutPhoto();
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }


    static class LedRunnable implements Runnable {
        private PL2303Driver mSerial;
        private Handler mHandler;
        private int delay = 60000;
//                private int delay = 5000;
        private Callback.Cancelable cancelable;
        private PL2303Driver.BaudRate mBaudrate = PL2303Driver.BaudRate.B19200;

        public LedRunnable(Handler handler, PL2303Driver serial) {
            mHandler = handler;
            mSerial = serial;
        }

        private void openUsbSerial(String s) {
            if (null == mSerial) {
                Toast.makeText(TerminalApplication.getTerminalContext(), "isComSerial_NULL ", Toast.LENGTH_SHORT).show();
                return;
            }
            if (mSerial.isConnected()) {
                Toast.makeText(TerminalApplication.getTerminalContext(), "isConnected ", Toast.LENGTH_SHORT).show();
                mBaudrate = PL2303Driver.BaudRate.B19200;
                if (!mSerial.InitByBaudRate(mBaudrate, 700)) {
                    if (!mSerial.PL2303Device_IsHasPermission()) {
                        Toast.makeText(TerminalApplication.getTerminalContext(), "cannot open, maybe no permission", Toast.LENGTH_SHORT).show();
                    }

                    if (mSerial.PL2303Device_IsHasPermission() && (!mSerial.PL2303Device_IsSupportChip())) {
                        Toast.makeText(TerminalApplication.getTerminalContext(), "cannot open, maybe this chip has no support, please use PL2303HXD / RA / EA chip.", Toast.LENGTH_SHORT).show();
                    }
                } else {

                    Toast.makeText(TerminalApplication.getTerminalContext(), "connected : ", Toast.LENGTH_SHORT).show();
                    setLedText(s);
                }
            }//isConnected
        }//openUsbSerial

        private List<Byte> makeTempdata28(String s) {
            char[] chars = s.toCharArray();
            byte tempData28Color = 0x01;
            byte tempData28Icon = 0x00;
            byte tempData28End = (byte) 0xff;
            int length = s.length();
            List<Byte> tempData28 = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                tempData28.add(tempData28Color);
                tempData28.add(tempData28Icon);
                tempData28.add((byte) chars[i]);
            }
            tempData28.add(tempData28End);
            return tempData28;
        }


        private byte makeCheckNum(List<Byte> list) {
            int sum = 0;
            for (int i = 1; i < list.size(); i++) {
                sum = (sum + list.get(i));
            }
            sum = (sum % 256);
            return (byte) sum;

        }

        private void setLedText(String s) {
            if (null == mSerial)
                return;
            if (!mSerial.isConnected())
                return;
            List<Byte> list = new ArrayList<>();
            byte head = 0x79;
            byte command1 = 0x77;
            byte command2 = 0x00;
            byte addr = 0x00;
            byte rsMode = 0x00;
            byte cs = 0x00;
            byte id = 0x01;
            // data
            byte tempData1 = 0x00;
            byte tempData2 = 0x00;
            byte tempData3 = 0x00;
            List<Byte> tempData4to20 = new ArrayList<>();
            for (int i = 4; i < 21; i++) {
                byte temp = 0x00;
                tempData4to20.add(temp);
            }
            byte tempData21 = 0x00;
            byte tempData22 = 0x0A;
            byte tempData23 = 0x00;
            byte tempData24 = 0x01;
            byte tempData25 = 0x01;
            byte tempData26 = 0x05;
            byte tempData27 = 0x00;
            list.add(head);
            list.add(command1);
            list.add(command2);
            list.add(addr);
            list.add(rsMode);
            list.add(cs);
            list.add(id);
            list.add(tempData1);
            list.add(tempData2);
            list.add(tempData3);
            list.addAll(tempData4to20);
            list.add(tempData21);
            list.add(tempData22);
            list.add(tempData23);
            list.add(tempData24);
            list.add(tempData25);
            list.add(tempData26);
            list.add(tempData27);
            list.addAll(makeTempdata28(s));
            list.add(makeCheckNum(list));
            list.add(head);
            byte[] bytes = new byte[list.size()];
            for (int i = 0; i < list.size(); i++) {
                bytes[i] = list.get(i);
            }

            int res = mSerial.write(bytes, list.size());
            if (res < 0) {
                return;
            }
        }


        @Override
        public void run() {
            Log.e("harisucici", "GET_LED");
            cancelable = x.http().get(getLEDParams(), new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Log.e("harisucici", "LED成功");
                    if (result != null) {
                        //harisucici
                        LedBean ledBean = new Gson().fromJson(result, LedBean.class);
                        if (ledBean.getCode() == 0) {
                            Log.e("harisucici", "LEDURL:" + ledBean.getData().getCode());
                            openUsbSerial(ledBean.getData().getCode());
                        } else {
                            Log.e("harisucici", "LEDURL:" + "NO DATA");
                            openUsbSerial("NO DATA");
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
//                    openUsbSerial("ERROR");
                    Logger.t("harisucici").e("检查LEDOnError。" + ex.getMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {
//                    openUsbSerial("CANCEL");
                    Logger.t("harisucici").i("检查LED取消。");
                }

                @Override
                public void onFinished() {
//                    openUsbSerial("FINISH");
                    Logger.t("harisucici").i("检查LEDFinished");
                }
            });
            mHandler.postDelayed(this, delay);

        }


        private RequestParams getLEDParams() {
            TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
            StringBuilder sb = new StringBuilder();
            sb.append(NetConst.GET_LED);
            sb.append(terminalBaseInfo.getDevice());
//            sb.append("3394412223422613");
            Log.e("harisucici", "检测LEDUrl:" + terminalBaseInfo.getDevice());
            RequestParams requestLEDParams = new RequestParams(sb.toString());
            return requestLEDParams;
        }
    }
}
